#!/usr/bin/env python
# -*- coding: UTF-8 -*-
'''
@Project ：zm_pom 
@File    ：driver.py
@IDE     ：PyCharm 
@Author  ：你的烂笔头
@Date    ：2025/6/6 18:50 
'''

import logging
import os

import urllib3  # 禁用安全请求警告
from selenium import webdriver
from selenium.webdriver.chrome.service import Service as ChromeService
from selenium.webdriver.edge.service import Service as EdgeService
from selenium.webdriver.firefox.service import Service as FirefoxService
from webdrivermanager_cn.chrome import ChromeDriverManager
from webdrivermanager_cn.geckodriver import GeckodriverManager
# from webdrivermanager_cn.microsoft import EdgeWebDriverManager
from common.logcof import log
from utils import get_conf

class WebDriver:
    os.environ['WDM_LOG'] = str(logging.NOTSET)  # 设置环境变量，禁用日志
    os.environ['WDM_SSL_VERIFY'] = '0'  # 禁用SSL验证
    urllib3.disable_warnings()  # 禁用安全请求警告
    install_path = "E:\Installation\chromedriver-win64"  # 后期配置到文件中
    @property
    def chrome(self) -> webdriver.Chrome:
        """
        创建并配置Chrome浏览器驱动

        :return: 配置好的Chrome浏览器驱动实例
        """
        try:
            # 配置Chrome浏览器选项
            chrome_options = webdriver.ChromeOptions()
            # 手动安装并设置Chrome驱动服务
            chrome_service = ChromeService(executable_path=ChromeDriverManager(path=self.install_path).install())
            # 配置Chrome浏览器参数
            arguments = [
                '--disable-extensions',#禁用拓展
                '--disable-features=Translate', # 禁用翻译
                '--hide-scrollbars', # 隐藏滚动条
                '--no-first-run', # 跳过首次欢迎界面
                '--disable-background-networking',
                '--disable-sync',
                '--disable-features=OptimizationHints',
            ]
            for arg in arguments:
                chrome_options.add_argument(arg)

            # 配置Chrome浏览器实验选项
            exclude_switches = [
                'enable-automation',
                'ignore-certificate-errors',
            ]
            prefs = {
                "credentials_enable_service": False,
                "profile.password_manager_enabled": False,
            }
            chrome_options.add_experimental_option('excludeSwitches', exclude_switches)
            chrome_options.add_experimental_option("prefs", prefs)

            # 创建Chrome浏览器驱动实例
            driver = webdriver.Chrome(options=chrome_options, service=chrome_service)
            driver.maximize_window()  # 最大化浏览器窗口
        except Exception as e:
            log.error('❌ Google Chrome failed to start')
            raise e
        else:
            log.info('✅ Google Chrome started successfully')
            return driver

    # @property
    # def edge(self) -> webdriver.Edge:
    #     """
    #     创建并配置Edge浏览器驱动
    #
    #     :return: 配置好的Edge浏览器驱动实例
    #     """
    #     try:
    #         # 自动安装并设置Edge驱动服务
    #         edge_service = EdgeService(executable_path=EdgeWebDriverManager(path=self.install_path).install())
    #         # 创建Edge浏览器驱动实例
    #         driver = webdriver.Edge(service=edge_service)
    #         driver.maximize_window()  # 最大化浏览器窗口
    #     except Exception as e:
    #         log.error('❌ Edge failed to start')
    #         raise e
    #     else:
    #         log.info('✅ Edge started successfully')
    #         return driver

    @property
    def firefox(self) -> webdriver.Firefox:
        """
        创建并配置Firefox浏览器驱动

        :return: 配置好的Firefox浏览器驱动实例
        """
        try:
            # 自动安装并设置Firefox驱动服务
            firefox_service = FirefoxService(executable_path=GeckodriverManager(path=self.install_path).install())
            # 创建Firefox浏览器驱动实例
            driver = webdriver.Firefox(service=firefox_service)
            driver.maximize_window()  # 最大化浏览器窗口
        except Exception as e:
            log.error('❌ Firefox failed to start')
            raise e
        else:
            log.info('✅ Firefox started successfully')
            return driver

    # @property
    # def ie(self) -> webdriver.Ie:
    #     """
    #     创建并配置IE浏览器驱动
    #
    #     :return: 配置好的IE浏览器驱动实例
    #     """
    #     try:
    #         # 自动安装并设置IE驱动服务
    #         ie_service = IeService(executable_path=IEDriverManager().install())
    #         # 创建IE浏览器驱动实例
    #         driver = webdriver.Ie(service=ie_service)
    #         driver.maximize_window()  # 最大化浏览器窗口
    #     except Exception as e:
    #         log.error('❌ Ie failed to start')
    #         raise e
    #     else:
    #         log.info('✅ Ie started successfully')
    #         return driver

    def select_browser(self):
        """
        根据配置选择对应的浏览器驱动

        :return: 选定的浏览器驱动实例
        """
        # 获取配置中的浏览器类型
        browser = str(get_conf.BROWSER).lower()
        try:
            # 动态调用对应浏览器驱动方法 python中类似java的反射
            driver = getattr(self, browser)
        except Exception:
            raise ValueError(
                '❌ wrong browser selection, please check, only allow one of: ["chrome", "firefox", "edge"]'
            )
        log.info('')  # 预留空行
        return driver


# 创建WebDriver实例，用于统一管理不同浏览器的驱动
web_driver = WebDriver()